/*
 * @Author: xiehangyun 
 * @Date: 2025-07-25 17:24:07 
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2025-10-15 16:26:43
 */
import React, { useEffect, useRef, useState } from 'react';
import styles from './fabricDemo.module.less';
import { observer } from 'mobx-react-lite';
import fabricApi from '@/api/fabricApi';
import * as fabric from 'fabric';

interface Iprops {
    children?: React.ReactNode;
}

const FabricDemo = observer((props: Iprops) => {
    const canvasRef = useRef<HTMLCanvasElement>(null);
    const fabricCanvasRef = useRef<fabric.Canvas | null>(null);
    const [generatedImage, setGeneratedImage] = useState<string>('');
    const [isLoading, setIsLoading] = useState<boolean>(false);

    useEffect(() => {
        if (!canvasRef.current) return;

        const fabricCanvas = new fabric.Canvas(canvasRef.current, {
            width: 400,
            height: 300,
            preserveObjectStacking: true,
        });

        fabricCanvasRef.current = fabricCanvas;

        // const rect = new fabric.Rect({
        //     left: 100,
        //     top: 100,
        //     width: 150,
        //     height: 100,
        //     fill: '#1890ff'
        // });
        // fabricCanvas.add(rect);

        const imageUrls = [
            'https://www-3dkeshihua.oss-cn-shanghai.aliyuncs.com/upload/1536_1152_141149_NvBb7saON.jpg?x-oss-process=image/resize,m_lfit,w_200,h_200',
            'https://www-3dkeshihua.oss-cn-shanghai.aliyuncs.com/317_336_97718_iilZGSVVbn4.png?x-oss-process=image/resize,m_lfit,w_200,h_200',
            'https://www-3dkeshihua.oss-cn-shanghai.aliyuncs.com/Bcwve6IUYSz.fif?x-oss-process=image/resize,m_lfit,w_200,h_200',
            'https://www-3dkeshihua.oss-cn-shanghai.aliyuncs.com/1024_1024_337725_cE_cqi-FvBI.png?x-oss-process=image/resize,m_lfit,w_200,h_200',
            'https://www-3dkeshihua.oss-cn-shanghai.aliyuncs.com/800_800_421648__waKY0V6NaA.jpg?x-oss-process=image/resize,m_lfit,w_200,h_200',
        ];

        const loadImagesRandomly = () => {
            imageUrls.forEach((url, index) => {
                const imgEl = new Image();
                imgEl.crossOrigin = 'anonymous';
                imgEl.onload = () => {
                    try {
                        const img = new fabric.FabricImage(imgEl);

                        const randomX = Math.random() * (fabricCanvas.width - 100);
                        const randomY = Math.random() * (fabricCanvas.height - 100);
                        const randomScale = 0.3 + Math.random() * 0.5;
                        img.scale(randomScale);
                        img.set({
                            left: randomX,
                            top: randomY,
                            selectable: true,
                            hasControls: true,
                            hasBorders: true,
                            crossOrigin: 'anonymous'
                        });
                        console.log(`加载图片 ${index + 1}:`, img);
                        fabricCanvas.add(img);
                        fabricCanvas.renderAll();
                    } catch (error) {
                        console.error(`创建图片对象失败 ${index + 1}:`, error);
                    }
                };
                imgEl.onerror = (error) => {
                    console.error(`加载图片失败 ${index + 1}:`, error);
                };
                imgEl.src = url;
            });
        };

        loadImagesRandomly();

        fabricCanvas.on('object:moving', (e: any) => {
            console.log('Object moving:', {
                type: e.target.type,
                position: { x: e.target.left, y: e.target.top }
            });
        });

        return () => {
            fabricCanvas.dispose();
            fabricCanvasRef.current = null;
        };
    }, []);

    const exportAndGenerateImage = async () => {
        if (!fabricCanvasRef.current) {
            console.error('Fabric canvas is not initialized');
            return;
        }

        try {
            setIsLoading(true);

            const fabricJson = fabricCanvasRef.current.toJSON();
            console.log('Exported Fabric JSON:', fabricJson);

            const canvasWidth = fabricCanvasRef.current?.width || 400;
            const canvasHeight = fabricCanvasRef.current?.height || 300;

            const response = await fabricApi.fabric_generate_image({ fabricJson, width: canvasWidth, height: canvasHeight });

            if (response && response.code === 200 && response.data && response.data.dataUrl) {
                setGeneratedImage(response.data.dataUrl);
                console.log('Successfully generated fabric image');
            } else {
                console.error('Failed to generate fabric image:', response);
            }
        } catch (error) {
            console.error('Error exporting and generating fabric image:', error);
        } finally {
            setIsLoading(false);
        }
    };

    return (
        <div className={styles.fabricDemo}>
            <h1 className={styles.page_title}>Fabric.js 图片合成导出 Demo</h1>

            <div className={styles.controls_section}>
                <button
                    className={styles.export_btn}
                    onClick={exportAndGenerateImage}
                    disabled={isLoading}
                >
                    {isLoading ? '处理中...' : '导出并生成图片'}
                </button>
            </div>

            <div className={styles.main_content}>
                <div className={styles.editor_card}>
                    <h2 className={styles.card_title}>编辑区域</h2>
                    <div className={styles.canvas_wrapper}>
                        <canvas
                            ref={canvasRef}
                            className={styles.canvas}
                            width={600}
                            height={400}
                        />
                    </div>
                </div>

                <div className={styles.preview_card}>
                    <h2 className={styles.card_title}>预览区域</h2>
                    <div className={styles.image_wrapper}>
                        {generatedImage ? (
                            <img
                                src={generatedImage}
                                alt="Generated"
                                className={styles.generated_img}
                            />
                        ) : (
                            <p className={styles.no_img_text}>暂无生成的图片</p>
                        )}
                    </div>
                </div>
            </div>
        </div>
    );
});

export default FabricDemo;